import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

// 类型定义
export interface SortConfig {
  field: string
  type: 'number' | 'string'
  order: 'asc' | 'desc'
  priority?: number // 添加优先级支持
}

export interface ColumnConfig {
  name: string
  shouldCompare: boolean
  isNumeric: boolean
  ignoreDigits: number
  comparisonResult: string
  diffCount: number // 添加差异数量统计
  examples: Array<{ excel1: any; excel2: any; rowNum1?: number; rowNum2?: number }>
}

export interface ComparisonResult {
  totalRows: number
  matchedRows: number
  differentRows: number
  onlyInFile1: number
  onlyInFile2: number
  differences: Array<{
    row: number
    type: 'different' | 'only-in-file1' | 'only-in-file2'
    content1: string | null
    content2: string | null
    fieldDifferences?: string[] // 添加字段级别的差异详情
  }>
  fieldComparisonResults?: Record<
    string,
    {
      status: 'identical' | 'different' | 'not-exist'
      diffCount: number
      examples: string[]
    }
  >
}

// 进度回调类型
export type ProgressCallback = (progress: number, stage: string) => void

// 比较数据类
interface CompareData {
  rowIndex: number
  rowData: any[]
}

export function useExcelData() {
  // 状态管理
  const excel1DataFrame = ref<any>(null)
  const excel2DataFrame = ref<any>(null)
  const excel1Headers = ref<string[]>([])
  const excel2Headers = ref<string[]>([])
  const excel1Preview = ref<any[]>([])
  const excel1Data = ref<any[]>([])
  const excel2Data = ref<any[]>([])
  const columnConfigs = ref<ColumnConfig[]>([])
  const sortConfigs = ref<SortConfig[]>([])
  const isLoadingExcel1 = ref(false)
  const isLoadingExcel2 = ref(false)

  // 配置选项
  const ignoreCase = ref(true)
  const ignoreSpaces = ref(true)
  const compareMode = ref('key')

  // 批处理大小，用于内存优化
  const BATCH_SIZE = 1000

  // 安全数值转换 - 参考Python实现
  const safeConvertToNumeric = (value: any): number => {
    try {
      if (value === null || value === undefined) {
        return 0
      }
      if (typeof value === 'number') {
        return isNaN(value) ? 0 : value
      }
      if (typeof value === 'string') {
        // 移除可能的空格和特殊字符
        const cleanedValue = value.trim().replace(/,/g, '')
        if (cleanedValue === '' || cleanedValue.toLowerCase() === 'nan') {
          return 0
        }
        const parsed = parseFloat(cleanedValue)
        return isNaN(parsed) ? 0 : parsed
      }
      return 0
    } catch {
      return 0
    }
  }

  // 安全字符串转换 - 参考Python实现
  const safeConvertToString = (value: any): string => {
    try {
      if (value === null || value === undefined) {
        return ''
      }
      if (typeof value === 'number') {
        // 如果是整数，去掉小数点后的.0
        if (Number.isInteger(value)) {
          return String(Math.floor(value))
        }
        return String(value)
      }
      return String(value).trim()
    } catch {
      return ''
    }
  }

  // 比较两个值 - 支持数值精度控制
  const compareValues = (val1: any, val2: any, config: ColumnConfig): boolean => {
    if (!config.shouldCompare) {
      console.log(`跳过比较 ${config.name} - shouldCompare=false`)
      return true
    }

    // 处理null/undefined情况
    if ((val1 === null || val1 === undefined) && (val2 === null || val2 === undefined)) {
      console.log(`${config.name}: 两个值都为null/undefined，认为相同`)
      return true
    }
    if (val1 === null || val1 === undefined || val2 === null || val2 === undefined) {
      console.log(`${config.name}: 一个值为null/undefined，认为不同: val1=${val1}, val2=${val2}`)
      return false
    }

    if (config.isNumeric) {
      try {
        const num1 = safeConvertToNumeric(val1)
        const num2 = safeConvertToNumeric(val2)

        console.log(`${config.name}: 数值比较 - val1=${val1}(${num1}), val2=${val2}(${num2})`)

        if (config.ignoreDigits > 0) {
          const factor = Math.pow(10, config.ignoreDigits)
          const result = Math.floor(num1 * factor) === Math.floor(num2 * factor)
          console.log(`${config.name}: 忽略小数位比较结果: ${result}`)
          return result
        }
        const result = num1 === num2
        console.log(`${config.name}: 精确数值比较结果: ${result}`)
        return result
      } catch (error) {
        console.log(`${config.name}: 数值比较出错: ${error}`)
        return false
      }
    }

    // 字符串比较
    const str1 = normalizeValue(val1)
    const str2 = normalizeValue(val2)
    const result = str1 === str2
    console.log(
      `${config.name}: 字符串比较 - "${val1}"("${str1}") vs "${val2}"("${str2}") = ${result}`,
    )
    return result
  }

  // 排序数据 - 使用原生数组排序，支持多字段排序
  const sortDataFrame = (dataObj: any) => {
    if (sortConfigs.value.length === 0) return dataObj

    try {
      const data = dataObj.data || dataObj
      if (!Array.isArray(data) || data.length <= 1) return dataObj

      const headers = data[0]
      const dataRows = data.slice(1) // 去掉标题行

      // 按优先级排序配置
      const sortedConfigs = [...sortConfigs.value].sort(
        (a, b) => (a.priority || 0) - (b.priority || 0),
      )

      // 多字段排序
      const sortedRows = dataRows.sort((rowA: any[], rowB: any[]) => {
        for (const config of sortedConfigs) {
          const colIndex = headers.findIndex((h: string) => h === config.field)
          if (colIndex === -1) {
            console.warn(`排序字段 '${config.field}' 不存在，跳过`)
            continue
          }

          let valA = rowA[colIndex]
          let valB = rowB[colIndex]

          // 根据字段类型转换数据
          if (config.type === 'number') {
            valA = safeConvertToNumeric(valA)
            valB = safeConvertToNumeric(valB)
          } else {
            valA = safeConvertToString(valA)
            valB = safeConvertToString(valB)
          }

          let comparison = 0
          if (valA < valB) comparison = -1
          else if (valA > valB) comparison = 1

          if (comparison !== 0) {
            return config.order === 'asc' ? comparison : -comparison
          }
        }
        return 0
      })

      const sortedData = [headers, ...sortedRows]

      return {
        data: sortedData,
        shape: [sortedRows.length, headers.length],
        columns: headers,
      }
    } catch (error) {
      console.error('排序失败:', error)
      ElMessage.error(`排序失败: ${error}`)
      return dataObj
    }
  }

  // 标准化值以进行比较
  const normalizeValue = (value: any): string => {
    if (value === null || value === undefined) {
      return ''
    }

    let strValue = String(value)

    if (ignoreCase.value) {
      strValue = strValue.toLowerCase()
    }

    if (ignoreSpaces.value) {
      strValue = strValue.trim().replace(/\s+/g, ' ')
    }

    return strValue
  }

  // 比较两行是否相等 - 优化版本
  const compareRows = (
    row1: any[],
    row2: any[],
    configs: ColumnConfig[],
  ): {
    isEqual: boolean
    differences: string[]
  } => {
    if (!row1 || !row2) {
      return { isEqual: false, differences: ['行数据缺失'] }
    }

    const differences: string[] = []
    let isEqual = true

    // 只比较需要对比的字段
    for (let i = 0; i < Math.min(row1.length, configs.length); i++) {
      const config = configs[i]
      if (!config.shouldCompare) continue

      const val1 = i < row1.length ? row1[i] : null
      const val2 = i < row2.length ? row2[i] : null

      if (!compareValues(val1, val2, config)) {
        isEqual = false
        differences.push(`${config.name}: ${val1} -> ${val2}`)
      }
    }

    return { isEqual, differences }
  }

  // 使用 XLSX 对比数据 - 优化版本，支持进度回调
  const compareDataFrames = async (
    dataObj1: any,
    dataObj2: any,
    data1: any[],
    data2: any[],
    progressCallback?: ProgressCallback,
  ): Promise<ComparisonResult> => {
    const result: ComparisonResult = {
      totalRows: Math.max(
        dataObj1.shape?.[0] || data1.length - 1,
        dataObj2.shape?.[0] || data2.length - 1,
      ),
      matchedRows: 0,
      differentRows: 0,
      onlyInFile1: 0,
      onlyInFile2: 0,
      differences: [],
      fieldComparisonResults: {},
    }

    // 初始化字段级别的比较结果
    const fieldResults: Record<
      string,
      {
        status: 'identical' | 'different' | 'not-exist'
        diffCount: number
        examples: string[]
      }
    > = {}

    excel1Headers.value.forEach((header) => {
      fieldResults[header] = {
        status: 'identical',
        diffCount: 0,
        examples: [],
      }
    })

    try {
      if (compareMode.value === 'position') {
        progressCallback?.(10, '开始按位置对比...')

        // 按位置对比 - 批处理优化
        const maxRows = Math.max(data1.length - 1, data2.length - 1) // 减1因为第一行是标题
        const totalBatches = Math.ceil(maxRows / BATCH_SIZE)

        for (let batch = 0; batch < totalBatches; batch++) {
          const startIdx = batch * BATCH_SIZE + 1 // +1跳过标题行
          const endIdx = Math.min((batch + 1) * BATCH_SIZE + 1, maxRows + 1)

          progressCallback?.(
            10 + (batch / totalBatches) * 80,
            `处理第 ${startIdx} 到 ${endIdx} 行...`,
          )

          for (let i = startIdx; i < endIdx; i++) {
            const row1 = i < data1.length ? data1[i] : null
            const row2 = i < data2.length ? data2[i] : null

            if (row1 === null) {
              result.onlyInFile2++
              result.differences.push({
                row: i,
                type: 'only-in-file2',
                content1: null,
                content2: JSON.stringify(row2),
              })
            } else if (row2 === null) {
              result.onlyInFile1++
              result.differences.push({
                row: i,
                type: 'only-in-file1',
                content1: JSON.stringify(row1),
                content2: null,
              })
            } else {
              const comparison = compareRows(row1, row2, columnConfigs.value)
              if (comparison.isEqual) {
                result.matchedRows++
              } else {
                result.differentRows++
                result.differences.push({
                  row: i,
                  type: 'different',
                  content1: JSON.stringify(row1),
                  content2: JSON.stringify(row2),
                  fieldDifferences: comparison.differences,
                })

                // 更新字段级别的差异统计
                comparison.differences.forEach((diff) => {
                  const fieldName = diff.split(':')[0]
                  if (fieldResults[fieldName]) {
                    fieldResults[fieldName].status = 'different'
                    fieldResults[fieldName].diffCount++
                    if (fieldResults[fieldName].examples.length < 3) {
                      fieldResults[fieldName].examples.push(`行${i}: ${diff}`)
                    }
                  }
                })
              }
            }
          }

          // 让出控制权，避免阻塞UI
          await new Promise((resolve) => setTimeout(resolve, 0))
        }
      } else {
        // 按排序字段对比 - 使用优化的Map结构
        progressCallback?.(10, '验证排序字段...')

        const headers1 = data1[0] || []
        const headers2 = data2[0] || []

        // 检查是否有排序配置
        if (sortConfigs.value.length === 0) {
          ElMessage.error('请至少添加一个排序字段作为对比依据')
          return result
        }

        // 获取所有排序字段在各自文件中的索引
        const sortFieldIndices1: number[] = []
        const sortFieldIndices2: number[] = []

        for (const config of sortConfigs.value) {
          const index1 = headers1.findIndex((h: string) => h === config.field)
          const index2 = headers2.findIndex((h: string) => h === config.field)

          if (index1 === -1 || index2 === -1) {
            ElMessage.error(`排序字段 "${config.field}" 在某个Excel文件中不存在`)
            return result
          }

          sortFieldIndices1.push(index1)
          sortFieldIndices2.push(index2)
        }

        progressCallback?.(20, '构建表2索引映射...')

        // 构建表2的索引Map
        const data2Map = new Map<string, CompareData>()
        for (let i = 1; i < data2.length; i++) {
          // 从1开始，跳过标题行
          const row2 = data2[i]
          const keyParts = sortFieldIndices2.map((idx) => normalizeValue(row2[idx] || ''))
          const uniqueKey = keyParts.join('-')

          data2Map.set(uniqueKey, {
            rowIndex: i,
            rowData: row2,
          })
        }

        progressCallback?.(40, '构建表1索引映射...')

        // 构建表1的索引Map
        const data1Map = new Map<string, CompareData>()
        for (let i = 1; i < data1.length; i++) {
          // 从1开始，跳过标题行
          const row1 = data1[i]
          const keyParts = sortFieldIndices1.map((idx) => normalizeValue(row1[idx] || ''))
          const uniqueKey = keyParts.join('-')

          data1Map.set(uniqueKey, {
            rowIndex: i,
            rowData: row1,
          })
        }

        progressCallback?.(60, '分析差异数据...')

        // 找出只在表1中存在的行
        for (const [key, { rowData, rowIndex }] of data1Map.entries()) {
          if (!data2Map.has(key)) {
            result.onlyInFile1++
            result.differences.push({
              row: rowIndex,
              type: 'only-in-file1',
              content1: JSON.stringify(rowData),
              content2: null,
            })
          }
        }

        // 找出只在表2中存在的行
        for (const [key, { rowData, rowIndex }] of data2Map.entries()) {
          if (!data1Map.has(key)) {
            result.onlyInFile2++
            result.differences.push({
              row: rowIndex,
              type: 'only-in-file2',
              content1: null,
              content2: JSON.stringify(rowData),
            })
          }
        }

        progressCallback?.(80, '比较匹配行...')

        // 比较两个表中都存在的行
        for (const [key, { rowData: row1, rowIndex: index1 }] of data1Map.entries()) {
          const matchingData = data2Map.get(key)
          if (matchingData) {
            const { rowData: row2 } = matchingData
            const comparison = compareRows(row1, row2, columnConfigs.value)

            if (comparison.isEqual) {
              result.matchedRows++
            } else {
              result.differentRows++
              result.differences.push({
                row: index1,
                type: 'different',
                content1: JSON.stringify(row1),
                content2: JSON.stringify(row2),
                fieldDifferences: comparison.differences,
              })

              // 更新字段级别的差异统计
              comparison.differences.forEach((diff) => {
                const fieldName = diff.split(':')[0]
                if (fieldResults[fieldName]) {
                  fieldResults[fieldName].status = 'different'
                  fieldResults[fieldName].diffCount++
                  if (fieldResults[fieldName].examples.length < 3) {
                    fieldResults[fieldName].examples.push(`行${index1}: ${diff}`)
                  }
                }
              })
            }
          }
        }
      }

      // 检查Excel2中是否有额外的列
      excel2Headers.value.forEach((header) => {
        if (!excel1Headers.value.includes(header)) {
          fieldResults[header] = {
            status: 'not-exist',
            diffCount: data2.length - 1, // 减1因为标题行
            examples: ['Excel1中不存在此列'],
          }
        }
      })

      result.fieldComparisonResults = fieldResults
      progressCallback?.(100, '对比完成')
    } catch (error) {
      console.error('对比过程中出错:', error)
      throw new Error(`对比失败: ${error}`)
    }

    return result
  }

  // 分析每列的差异情况 - 优化版本
  const analyzeColumnDifferences = (data1: any[], data2: any[]) => {
    console.log('开始分析列差异...')
    console.log('data1 length:', data1.length, 'data2 length:', data2.length)
    console.log('data1 sample:', data1.slice(0, 3))
    console.log('data2 sample:', data2.slice(0, 3))

    const headers1 = data1[0] || []
    const headers2 = data2[0] || []

    console.log('headers1:', headers1)
    console.log('headers2:', headers2)

    // 生成表2的索引Map
    const data2Map = new Map<string, CompareData>()

    // 获取排序字段在表2中的索引
    const sortFieldIndices2: number[] = []
    for (const sortConfig of sortConfigs.value) {
      const index2 = headers2.findIndex((h: string) => h === sortConfig.field)
      if (index2 !== -1) {
        sortFieldIndices2.push(index2)
      }
    }

    // 构建表2的索引Map
    if (compareMode.value === 'key' && sortFieldIndices2.length > 0) {
      for (let i = 1; i < data2.length; i++) {
        // 从1开始，跳过标题行
        const row2 = data2[i]
        const keyParts = sortFieldIndices2.map((idx) => normalizeValue(row2[idx] || ''))
        const uniqueKey = keyParts.join('-')

        data2Map.set(uniqueKey, {
          rowIndex: i,
          rowData: row2,
        })
      }
    }

    console.log(`表2索引Map构建完成，共 ${data2Map.size} 条记录`)

    columnConfigs.value.forEach((config, configIndex) => {
      console.log(`分析列 ${config.name} (索引: ${configIndex})`)

      // 重置统计
      config.comparisonResult = ''
      config.diffCount = 0
      config.examples = []

      if (!config.shouldCompare) {
        console.log(`跳过列 ${config.name} - 未选择对比`)
        return
      }

      const colIndex1 = headers1.findIndex((h: string) => h === config.name)
      const colIndex2 = headers2.findIndex((h: string) => h === config.name)

      console.log(`列 ${config.name} 在文件中的索引: file1=${colIndex1}, file2=${colIndex2}`)

      if (colIndex1 === -1 || colIndex2 === -1) {
        config.comparisonResult = 'not-exist'
        console.log(`列 ${config.name} 在某个文件中不存在`)
        return
      }

      let isDifferent = false
      const examples = []

      // 获取排序字段在表1中的索引
      const sortFieldIndices1: number[] = []
      for (const sortConfig of sortConfigs.value) {
        const index1 = headers1.findIndex((h: string) => h === sortConfig.field)
        if (index1 !== -1) {
          sortFieldIndices1.push(index1)
        }
      }

      console.log(`开始比较列 ${config.name}，表1数据行数: ${data1.length - 1}`)

      // 遍历表1数据
      for (let i = 1; i < data1.length; i++) {
        // 从1开始，跳过标题行
        const row1 = data1[i]
        let matchingData: CompareData | null = null

        if (compareMode.value === 'key' && sortFieldIndices1.length > 0) {
          // 生成表1当前行的唯一索引
          const keyParts = sortFieldIndices1.map((idx) => normalizeValue(row1[idx] || ''))
          const uniqueKey = keyParts.join('-')

          // 在表2的Map中查找匹配数据
          matchingData = data2Map.get(uniqueKey) || null

          if (!matchingData) {
            console.log(`行 ${i} (key: ${uniqueKey}) 在表2中不存在`)

            // 当数据在表2中找不到时，记录异常信息
            isDifferent = true
            config.diffCount++

            // 获取排序字段的值用于异常记录
            const sortFieldValues = sortConfigs.value
              .map((sortConfig) => {
                const fieldIndex = headers1.findIndex((h: string) => h === sortConfig.field)
                return fieldIndex !== -1 ? row1[fieldIndex] : ''
              })
              .join('-')

            console.log(`发现异常: 行${i}在表2中不存在，排序字段值: ${sortFieldValues}`)

            if (examples.length < 3) {
              examples.push({
                excel1: colIndex1 < row1.length ? row1[colIndex1] : null,
                excel2: `表2中不存在(排序字段: ${sortFieldValues})`,
                rowNum1: i,
                rowNum2: -1, // 表示在表2中不存在
              })
            }
            continue
          }
        } else {
          // 按位置对比
          if (i < data2.length) {
            matchingData = {
              rowIndex: i,
              rowData: data2[i],
            }
          } else {
            console.log(`行 ${i} 在表2中没有对应位置的数据`)

            // 按位置对比时，如果表2中没有对应位置的数据，也记录异常
            isDifferent = true
            config.diffCount++

            console.log(`发现异常: 行${i}在表2中没有对应位置的数据`)

            if (examples.length < 3) {
              examples.push({
                excel1: colIndex1 < row1.length ? row1[colIndex1] : null,
                excel2: `表2中不存在(位置${i})`,
                rowNum1: i,
                rowNum2: -1, // 表示在表2中不存在
              })
            }
            continue
          }
        }

        // 比较对应列的值
        const val1 = colIndex1 < row1.length ? row1[colIndex1] : null
        const val2 =
          colIndex2 < matchingData.rowData.length ? matchingData.rowData[colIndex2] : null

        console.log(
          `行 ${i}, 列 ${colIndex1} | ${colIndex2} ${config.name}: val1="${val1}", val2="${val2}"`,
        )

        if (!compareValues(val1, val2, config)) {
          isDifferent = true
          config.diffCount++

          console.log(`发现差异: ${val1} != ${val2}`)

          if (examples.length < 3) {
            examples.push({
              excel1: val1,
              excel2: val2,
              rowNum1: i,
              rowNum2: matchingData.rowIndex,
            })
          }
        }
      }

      config.comparisonResult = isDifferent ? 'different' : 'identical'
      config.examples = examples

      console.log(
        `列 ${config.name} 分析完成: ${config.comparisonResult}, 差异数量: ${config.diffCount}`,
      )
    })

    console.log('列差异分析完成')
  }

  // 排序配置管理
  const addSortConfig = () => {
    if (excel1Headers.value.length === 0) return

    const newPriority = Math.max(...sortConfigs.value.map((c) => c.priority || 0), 0) + 1
    sortConfigs.value.push({
      field: excel1Headers.value[0],
      type: 'string',
      order: 'asc',
      priority: newPriority,
    })
  }

  const removeSortConfig = (index: number) => {
    sortConfigs.value.splice(index, 1)
  }

  const copySortConfig = (index: number) => {
    const config = { ...sortConfigs.value[index] }
    config.priority = Math.max(...sortConfigs.value.map((c) => c.priority || 0), 0) + 1
    sortConfigs.value.splice(index + 1, 0, config)
  }

  const updateSortConfig = (index: number, field: string, value: any) => {
    if (sortConfigs.value[index]) {
      if (field === 'field') {
        sortConfigs.value[index].field = value
      } else if (field === 'type') {
        sortConfigs.value[index].type = value
      } else if (field === 'order') {
        sortConfigs.value[index].order = value
      } else if (field === 'priority') {
        sortConfigs.value[index].priority = value
      }
    }
  }

  // 列配置管理
  const updateColumnConfig = (index: number, field: string, value: any) => {
    if (columnConfigs.value[index]) {
      if (field === 'shouldCompare') {
        columnConfigs.value[index].shouldCompare = value
      } else if (field === 'isNumeric') {
        columnConfigs.value[index].isNumeric = value
      } else if (field === 'ignoreDigits') {
        columnConfigs.value[index].ignoreDigits = value
      }
    }
  }

  const selectAllColumns = () => {
    columnConfigs.value.forEach((config) => (config.shouldCompare = true))
    ElMessage.success('已全选所有字段')
  }

  const deselectAllColumns = () => {
    columnConfigs.value.forEach((config) => (config.shouldCompare = false))
    ElMessage.success('已取消选择所有字段')
  }

  // 清空对比结果
  const clearComparisonResults = () => {
    columnConfigs.value.forEach((config) => {
      config.comparisonResult = ''
      config.diffCount = 0
      config.examples = []
    })
  }

  // 获取内存使用情况（浏览器环境的简化版本）
  const getMemoryUsage = (): { used: number; total: number; percentage: number } => {
    try {
      // @ts-ignore - performance.memory 可能不存在
      const memory = performance.memory
      if (memory) {
        const used = memory.usedJSHeapSize / 1024 / 1024 // MB
        const total = memory.totalJSHeapSize / 1024 / 1024 // MB
        const percentage = (used / total) * 100
        return { used, total, percentage }
      }
    } catch {
      // 如果不支持，返回默认值
    }
    return { used: 0, total: 0, percentage: 0 }
  }

  // 读取Excel文件
  const readExcelFile = async (file: File, fileNum: number) => {
    if (fileNum === 1) {
      isLoadingExcel1.value = true
    } else {
      isLoadingExcel2.value = true
    }

    try {
      // 使用 XLSX 库读取 Excel 文件
      const arrayBuffer = await file.arrayBuffer()
      const workbook = XLSX.read(arrayBuffer, { type: 'array' })
      const sheetName = workbook.SheetNames[0]
      const sheet = workbook.Sheets[sheetName]

      // 转换为二维数组格式 [headers, row1, row2, ...]
      const data = XLSX.utils.sheet_to_json(sheet, { header: 1 }) as any[][]

      console.log('读取Excel文件成功')
      console.log('原始数据:', data)

      if (data.length === 0) {
        throw new Error('Excel文件为空')
      }

      if (fileNum === 1) {
        // 设置DataFrame兼容对象
        excel1DataFrame.value = { data, shape: [data.length - 1, data[0]?.length || 0] }

        const headers = data[0] as string[]
        console.log('excel1Headers:', headers)
        excel1Headers.value = headers

        // 数据已经是正确的格式 [headers, row1, row2, ...]
        excel1Data.value = data

        // 设置预览数据（前5行）
        const previewRows = Math.min(6, data.length) // 包含标题行，所以是6行
        excel1Preview.value = data.slice(0, previewRows)

        // 初始化列配置 - 默认所有列为文本类型
        columnConfigs.value = headers.map((header: string) => {
          return {
            name: header,
            shouldCompare: true,
            isNumeric: false, // 默认为文本类型，用户可手动调整
            ignoreDigits: 0,
            comparisonResult: '',
            diffCount: 0,
            examples: [],
          }
        })

        // 如果没有排序配置，添加一个默认的排序配置
        if (sortConfigs.value.length === 0 && headers.length > 0) {
          sortConfigs.value.push({
            field: headers[0],
            type: 'string',
            order: 'asc',
            priority: 1,
          })
        }
      } else {
        // 设置DataFrame兼容对象
        excel2DataFrame.value = { data, shape: [data.length - 1, data[0]?.length || 0] }

        const headers = data[0] as string[]
        excel2Headers.value = headers
        console.log('excel2Headers:', headers)

        // 数据已经是正确的格式 [headers, row1, row2, ...]
        excel2Data.value = data
        console.log('excel2Data:', data)
      }
    } catch (error) {
      console.error('Excel文件读取失败:', error)
      ElMessage.error('Excel文件读取失败，请重试')
    } finally {
      if (fileNum === 1) {
        isLoadingExcel1.value = false
      } else {
        isLoadingExcel2.value = false
      }
    }
  }

  return {
    // 状态
    excel1DataFrame,
    excel2DataFrame,
    excel1Headers,
    excel2Headers,
    excel1Preview,
    excel1Data,
    excel2Data,
    columnConfigs,
    sortConfigs,
    isLoadingExcel1,
    isLoadingExcel2,
    ignoreCase,
    ignoreSpaces,
    compareMode,

    // 核心方法
    readExcelFile,
    sortDataFrame,
    compareDataFrames,
    analyzeColumnDifferences,

    // 排序配置管理
    addSortConfig,
    removeSortConfig,
    copySortConfig,
    updateSortConfig,

    // 列配置管理
    updateColumnConfig,
    selectAllColumns,
    deselectAllColumns,

    // 工具方法
    normalizeValue,
    compareValues,
    safeConvertToNumeric,
    safeConvertToString,
    clearComparisonResults,
    getMemoryUsage,

    // 常量
    BATCH_SIZE,
  }
}
